package com.wujilee.wujileemybatisdynamicsql.controller;


import com.wujilee.wujileemybatisdynamicsql.entity.User;
import com.wujilee.wujileemybatisdynamicsql.mapper.UserDynamicSqlSupport;
import com.wujilee.wujileemybatisdynamicsql.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

/**
 * @author liwuji
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserMapper userMapper;

    @GetMapping
    public User getUser(Long id) {
        return userMapper.selectOne(dsl -> dsl.where(UserDynamicSqlSupport.user.userId, isEqualTo(id))).orElse(null);
    }

    @PostMapping
    public User getUser(@RequestBody User user) {
        userMapper.insert(user);
        return user;
    }


    @PostMapping("update")
    public String getUser(String name, Long id) {
        userMapper.update(
                dsl -> dsl.set(UserDynamicSqlSupport.user.username).equalTo(name)
                        .where(UserDynamicSqlSupport.user.userId, isEqualTo(id))
        );
        return "success";
    }


    @PostMapping("delete")
    public String delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
        return "success";
    }


}
